/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.util.Vector;

/**
 *
 * @author tfuru
 */
public class Executor extends Thread {

    private boolean m_alive;
    private Vector commands;
    private int m_sleep_time = 0;

    public Executor() {
        this(500);
    }

    public Executor(int sleep_time) {
        this.m_alive = true;
        this.commands = new Vector();
        this.m_sleep_time = sleep_time;
    }

    public void execute(Runnable command) {
        synchronized (this.commands) {
            this.commands.addElement(command);
        }
    }

    public void run() {
        while (m_alive) {
            while (getCommandSize() > 0) {
                if (!m_alive) {
                    break;
                }
                Runnable command = null;
                //synchronized (this.commands) {
                command = (Runnable) this.commands.firstElement();
                this.commands.removeElement(command);
                this.commands.trimToSize();
                //}
                if (command != null) {
                    command.run();
                }
                if (m_sleep_time > 0) {
                    try {
                        Thread.sleep(m_sleep_time);
                    } catch (InterruptedException ex) {
                        //ex.printStackTrace();
                    }
                }
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                //ex.printStackTrace();
            }
        }
        this.m_alive = false;
        removeAllCommands();
    }

    public int getCommandSize() {
        int size = 0;
        synchronized (this.commands) {
            size = this.commands.size();
        }
        return size;
    }

    public boolean getAlive() {
        return this.m_alive;
    }

    public void removeAllCommands() {
        synchronized (this.commands) {
            if (this.commands.size() > 0) {
                this.commands.removeAllElements();
                this.commands.trimToSize();
            }
        }
    }

    public void shutdown() {
        this.m_alive = false;
    }
}

